package service

import (
	"fmt"
	"go_code/20220714gotest/daily-test/202209/26/customerManage/model"
)

// 该结构体，完成对Customer的操作，包括增删改查
type CustomerService struct {
	customers []model.Customer
	//声明一个字段表示当前切片中有多少个客户
	//该字段还可以作为新客户的id+1
	customerNum int
}

// 编写一个方法可以返回一个 *CustomerService
func NewCustomerSerivce() *CustomerService {
	//为了能够看到有客户在切片中，我们初始化一个客户
	customerService := &CustomerService{}
	customerService.customerNum = 1
	customer := model.NewCustomer(1, "张三", "男", 30, "121", "zs@souhu.com")
	customerService.customers = append(customerService.customers, customer)
	return customerService
}

// 返回客户切片
func (this *CustomerService) List() []model.Customer {
	return this.customers
}

// 编写添加客户的方法
// Add方法 将新的客户加入到 customers切片
func (this *CustomerService) Add(customer model.Customer) bool {
	this.customerNum++
	customer.Id = this.customerNum
	this.customers = append(this.customers, customer)
	return true
}

// 根据id删除客户(从切片中删除)
func (this *CustomerService) DeleteById(id int) bool {
	index := this.FindById(id)
	if index == -1 {
		return false
	}
	this.customers = append(this.customers[:index], this.customers[index+1:]...)
	return true
}

// 根据id删除客户(从切片中删除)
func (this *CustomerService) UpdateById() {
	id := -1
	fmt.Println("请输入您要修改的用户编号(-1)退出")
	fmt.Scanln(&id)
	//id==-1 放弃删除
	if id == -1 {
		fmt.Println("放弃修改，正在返回主界面...")
		return
	}
	index := this.FindById(id)
	if index == -1 {
		fmt.Println("修改失败，id不存在")
		return
	}
	fmt.Println("请输入修改后的姓名")
	name := ""
	fmt.Scanln(&name)
	fmt.Println("请输入修改后的性别")
	gender := ""
	fmt.Scanln(&gender)
	fmt.Println("请输入修改后的年龄")
	age := 0
	fmt.Scanln(&age)
	fmt.Println("请输入修改后的电话")
	phone := ""
	fmt.Println("请输入修改后的邮箱")
	email := ""
	fmt.Scanln(&email)
	this.customers[index] = model.NewCustomer(id, name, gender, age, phone, email)
	fmt.Println("修改成功，正在返回主界面...")
}

// 根据id查找客户在切片中对应的下标
func (this *CustomerService) FindById(id int) int {
	index := -1
	for i := 0; i < len(this.customers); i++ {
		if id == this.customers[i].Id {
			index = i
		}
	}
	return index
}
